from django.core.files.uploadedfile import InMemoryUploadedFile
import oss2
from django.conf import settings

from common.errors import InternalFailure


class AliOssService:
    def upload(self, file: InMemoryUploadedFile, save_dir: str) -> str:
        auth = oss2.Auth(settings.OSS_ACCESS_KEY_ID, settings.OSS_ACCESS_KEY_SECRET)
        bucket = oss2.Bucket(auth, settings.OSS_ENDPOINT, settings.OSS_BUCKET_NAME)
        res = bucket.put_object(save_dir + "/" + file.name, file.file)
        if res.status != 200:
            raise InternalFailure("文件上传失败：" + res.resp.response.reason)
        return res.resp.response.url
